
<template>
  <div class='home'>
    <div class='mask'>
      <button @click='toggle2d3d()'>2D3D切换</button>
      <button @click='addPoints()'>jiji</button>
    </div>
    <div id='map'></div>
    <div id='cesiumContainer'></div>
    <button @click='addSate()'>加载卫星</button>
  </div>
</template>

<script>
/* global Cesium */
import 'ol/ol.css'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import { Map, View } from 'ol'
import OLCesium from 'olcs/OLCesium.js'

// 卫星相关 引入封装好的js
import { CesiumTimelineHelper } from '../modules/CesiumTimelineHelper';
import { SatelliteProperties } from '../modules/SatelliteProperties';
export default {
  name: 'HomeView',
  data () {
    return {
      toggle: true,
      Androidload: { // 放双行根数数据的
        AndroidloadSatellitesArr: []
      }
    }
  },
  methods: {
    // 初始化地图
    initOlMap () {
      window.ol2dMap = new Map({
        target: 'map', // 指向对象
        layers: [
          // 图层
          new TileLayer({
            // 这里定义的是平铺图层
            source: new OSM(
              // {
              //   url: 'http://t{0-7}.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f',
              //   crossOrigin: 'anonymous'
              // }
            )
          })
        ],
        view: new View({
          projection: 'EPSG:4326',
          center: [118.792207, 32.133476],
          zoom: 5
        })
      })
    },
    // 2D3D切换
    toggle2d3d () {
      this.toggle = !this.toggle ? window.ol3d.scene_.morphTo3D(0) : window.ol3d.scene_.morphTo2D(0)
    },
    init3D (Cesium) { // 初始化地球 type
      const provider = new Cesium.TileMapServiceImageryProvider({
        url: Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII')
      })
      Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(60.0, 20.0, 140.0, 60.0)
      const options = { // 出厂默认配置项
        navigationHelpButton: false, // 是否显示帮助信息控件
        shouldAnimate: true, // 按照路线飞必须加这个
        baseLayerPicker: false, // 是否显示图层选择控件,
        geocoder: false,
        imageryProvider: provider,
        fullscreenButton: false // 全屏按钮
      }
      window.viewer = new Cesium.Viewer('cesiumContainer', options)
      window.viewer.scene.debugShowFramesPerSecond = true
    },
    addPoints () {
      // click,dblclick,singleclick 区别联系

      // dblclick 会触发两次click，不会触发singleclick.

      // singleclick会在click触发之后250毫秒后触发。

      window.ol3d.map_.on('click', (e) => {
        window.ol3d.getDataSourceDisplay().defaultDataSource.entities.add({
          position: Cesium.Cartesian3.fromDegrees(e.coordinate[0], e.coordinate[1]),
          point: {
            color: Cesium.Color.RED,
            pixelSize: 10,
            outlineColor: Cesium.Color.RED,
            outlineWidth: 1
          }
        })
      })
    },

    // ***************************************** 卫星相关start ****************************************

    // 加载所有卫星相关
    loadWeiXingArr (AndroidloadSatellitesArr, colorArr) {
      const viewer = window.viewer
      let timeline = new CesiumTimelineHelper(viewer);
      AndroidloadSatellitesArr.forEach((item, i) => {
        let tleLine = AndroidloadSatellitesArr[i];
        let properties = new SatelliteProperties(tleLine.tle, tleLine.tags);
        let myColor = colorArr[i]
        let entities = {};
        // label
        const label = new Cesium.LabelGraphics({
          text: properties.name,
          scale: 0.5,
          font: '60px',
          fillColor: myColor,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          pixelOffset: new Cesium.Cartesian2(15, 0),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(10000, 6.0e7),
          pixelOffsetScaleByDistance: new Cesium.NearFarScalar(1.0e1, 10, 2.0e5, 1),
        });
        const labelEntity = this.createEntity(properties)
        labelEntity.label = label;
        entities.Label = labelEntity;
        // this.createEntity(properties,entity,'Label')
        // 轨道
        const path = new Cesium.PathGraphics({
          leadTime: (properties.orbit.orbitalPeriod * 60) / 2 + 5,
          trailTime: (properties.orbit.orbitalPeriod * 60) / 2 + 5,
          material: new Cesium.ColorMaterialProperty(myColor),
          resolution: 600,
          width: 2,
        });
        const pathEntity = this.createEntity(properties)
        pathEntity.path = path;
        entities.Orbit = pathEntity;
        // 模型
        // const model = new Cesium.ModelGraphics({
        //   uri: 'model3D/eam_026_AR.gltf',
        //   // uri: 'model3D/weixing.gltf',
        //   // minimumPixelSize: 75,
        //   minimumPixelSize: 75,
        //   // maximumScale: 1500
        // });
        // const modelEntity = this.createEntity(properties)
        // pathEntity.model = model;
        // entities.Model = modelEntity;
        const model = new Cesium.PointGraphics({
          pixelSize: 10, // default: 1
          color: myColor, // default: WHITE
        });
        const modelEntity = this.createEntity(properties)
        modelEntity.point = model;
        entities.Model = modelEntity;
        properties.createSampledPosition(viewer.clock, (sampledPosition) => {
          Object.entries(entities).forEach(([type, entity]) => {
            if (type === 'Orbit') {
              entity.position = properties.sampledPositionInertial;
              entity.orientation = new Cesium.VelocityOrientationProperty(
                properties.sampledPositionInertial
              );
            } else {
              entity.position = sampledPosition;
              entity.orientation = new Cesium.VelocityOrientationProperty(
                sampledPosition
              );
            }
          });
        });
        viewer.entities.add(entities.Model);
        viewer.entities.add(entities.Label);
        viewer.entities.add(entities.Orbit);
      })
    },
    // 数据解析
    showSatellites (SatellitesArr) {
      this.Androidload.AndroidloadSatellitesArr = []
      // 颜色数组
      var colorArr = []
      // 组织数据
      SatellitesArr.stript.forEach(item => {
        this.Androidload.AndroidloadSatellitesArr.push({
          tle: item.satelliteCode + '\n' + item.tle1 + '\n' + item.tle2,
          tags: ['Starlink']
        })
        colorArr.push(Cesium.Color.fromCssColorString(item.pathColor))
      })
      this.loadWeiXingArr(this.Androidload.AndroidloadSatellitesArr, colorArr) // 加载卫星轨道

    },
    // 创建卫星实体
    createEntity (properties) {
      return new Cesium.Entity({
        name: properties.name,
        description: {},
        position: properties.sampledPosition,
        viewFrom: new Cesium.Cartesian3(0, -3600000, 4200000),
        orientation: new Cesium.VelocityOrientationProperty(
          properties.sampledPosition
        ),
        flag: 'wx'
      });

    },
    // 给数据并加载
    addSate () {
      // 数据结构
      const SatellitesArr = {
        'mapType': '3D',
        'deduceTime': '未来12小时',
        'stript': [
          {
            'satelliteCode': 'GF4',
            'pathColor': '#FF0000',
            'tle1': '1 44257U 19029Y   21201.45986625  .00027092  00000-0  56677-3 0  9998',  // 第一行
            'tle2': '2 44257  52.9999  82.3366 0002434  86.4030 273.7254 15.45290633120123'   // 第二行
          },
          {
            'satelliteCode': 'GF2',
            'pathColor': '#329333',
            'tle1': '1 44281U 19029AY  21201.23836857  .00075644  00000-0  84719-3 0  9996 ',
            'tle2': '2 44281  52.9945 110.8023 0003690  79.6328 280.5100 15.62041078 51694'
          }
        ]
      }
      this.showSatellites(SatellitesArr)
    }
    // ***************************************** 卫星相关end ****************************************
  },
  mounted () {
    // 初始化 Cesium 
    this.init3D(Cesium)

    // 初始化 openlayers
    this.initOlMap()
    // olcesium初始化 ol2dMap 是openlayers绑定的地图对象
    window.ol3d = new OLCesium({ map: window.ol2dMap })
    // olcesium是否启用3D 为false 不能转3d
    window.ol3d.setEnabled(true)
    // 开启fps
    window.ol3d.scene_.debugShowFramesPerSecond = true
  }
}
</script>
<style lang="less" >
.home {
  width: 100%;
  height: 100%;
  display: flex;
  .mask {
    position: absolute;
    left: 50px;
    top: 50px;
    z-index: 99;
  }
}
#map,
#cesiumContainer {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid red;
}
</style>
